package com.njupt.towerssystem.services.impl;

import com.google.common.hash.BloomFilter;
import com.njupt.towerssystem.domain.ManageInfos;
import com.njupt.towerssystem.mapper.ManagerInfoMapper;
import com.njupt.towerssystem.services.RegisteUserService;
import lombok.Synchronized;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.locks.ReentrantLock;

@Service

public class RegisteUserServiceImpl implements RegisteUserService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ManagerInfoMapper managerInfoMapper;
    @Resource
    private BloomFilter<String> nameFilter;

    private ReentrantLock lock = new ReentrantLock();
    private static Queue<Integer> userids = new PriorityQueue<>();

    //当springboot工程启动时候自动调用本方法对userids集合填充数据
    @PostConstruct //当程序启动时自动启动本方法一次
    private void addNewUseridToArray(){
        int maxid = managerInfoMapper.findMaxUserid();
        for(int i=maxid;i<maxid+10000;i++){
            userids.add(i);
        }
    }

    //程序启动将所有的用户名存放到bloom过滤器的bit数组中
    @PostConstruct
    private void addUserToBloom(){
        List<String> allName = managerInfoMapper.findAllName();
        for(String name:allName){
            nameFilter.put(name);
        }
    }
    @Transactional//失误回溯 之后的增删改都需要
    @Override
    public boolean regUser(ManageInfos mi){
        //到数据库检查用户名是否存在 如果存在 则不注册
        //通过Bloom过滤器判断用户名是否存在 存在就返回false
        boolean isHas = nameFilter.mightContain(mi.getLoginname());
        if(isHas){
            return false;
        }

        //先查询最大的userid
        Integer maxid=0;
        lock.lock();
        try {
            if (userids.isEmpty()) {
                addNewUseridToArray();
            }
            maxid = userids.poll();
        }finally {
            lock.unlock();
        }

        //将最大值填充到对象中
        mi.setUserid(maxid);
        //将数据存放到数据库中
        managerInfoMapper.insertManagers(mi);
        //同时将该数据存放到redis缓存数据库
        stringRedisTemplate.opsForHash().put("manages",mi.getLoginname()+mi.getLoginpwd(),mi.toString());
        //将当前新建用户的用户名存放到Bloom过滤器里面
        nameFilter.put(mi.getLoginname());
        return true;
    }
}
